package com.piece.core.rabbit.producer;

import com.piece.core.framework.constant.RegisterConstants;
import com.piece.core.framework.support.dto.PayloadDTO;
import com.piece.core.framework.util.message.Message;
import com.piece.core.framework.util.message.MessageFactory;
import com.piece.core.framework.util.string.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;

@Slf4j
public class RabbitMessageProducer implements Message {

    private MessageFactory messageFactory;
    private RabbitTemplate rabbitTemplate;

    public RabbitMessageProducer(RabbitTemplate rabbitTemplate, MessageFactory messageFactory) {
        this.rabbitTemplate = rabbitTemplate;
        this.messageFactory = messageFactory;
    }

    @Override
    public boolean isDefault() {
        return true;
    }

    /**
     * 发送消息
     */
    @Override
    public void send(PayloadDTO payload) throws Exception {
        messageFactory.getOperator(payload.getOperator()).prepareSend(payload, "rabbitMessageProducer");
        convertAndSend(payload);
    }

    /**
     * 重新发送消息
     */
    @Override
    public void reSend(PayloadDTO payload) {
        convertAndSend(payload);
    }

    private void convertAndSend(PayloadDTO payload) {
        String exchange = StringUtil.isEmpty(payload.getExchange()) ? RegisterConstants.DELAY_EXCHANGE_NAME : payload.getExchange();
        String router = StringUtil.isEmpty(payload.getRouter()) ? RegisterConstants.DELAY_ROUTE_NAME : payload.getRouter();
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        if (StringUtil.isNotEmpty(payload.getExpiration())) {
            rabbitTemplate.convertAndSend(exchange, router, payload, message -> {
                // 给消息设置延迟毫秒值
                message.getMessageProperties().setExpiration(payload.getExpiration());
                return message;
            });
        } else {
            rabbitTemplate.convertAndSend(exchange, router, payload);
        }
    }
}
